<!-- 获取options网站地址
https://echarts.zhangmuchen.top/#/index -->
<template>
  <div :style="{ '--echarth-height': height }" ref="chartRef" class="echarts-container"></div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, watch, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

export default defineComponent({
  name: 'EChartsComponent',
  props: {
    options: {
      type: Object as () => echarts.EChartsOption,
      required: true,
    },
    h: {
      type: String,
      default: '400px',
    },
  },
  setup(props) {
    const chartRef = ref<HTMLElement | null>(null) // 引用 DOM 元素
    let chartInstance: echarts.ECharts | null = null // ECharts 实例

    // 初始化图表
    const initChart = () => {
      if (chartRef.value) {
        chartInstance = echarts.init(chartRef.value)
        chartInstance.setOption(props.options)
      }
    }

    // 监听 options 变化
    watch(
      () => props.options,
      (newOptions) => {
        if (chartInstance) {
          chartInstance.setOption(newOptions)
        }
      },
      { deep: true },
    )

    // 组件挂载时初始化图表
    onMounted(() => {
      initChart()
    })

    // 组件销毁时销毁图表实例
    onBeforeUnmount(() => {
      if (chartInstance) {
        chartInstance.dispose()
      }
    })

    return {
      chartRef,
      height: props.h,
    }
  },
})
</script>

<style scoped>
.echarts-container {
  width: 100%;
  height: var(--echarth-height);
}
</style>
